package tools.project.controller.action {
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.events.Event;
	import flash.events.NativeProcessExitEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	import flash.utils.setTimeout;
	
	import kiwi.action.Action;
	import kiwi.debug.Log;
	import kiwi.util.sprintf;
	
	import tools.model.EditorConfig;
	import tools.utils.SaveSmallPackageUtil;

	/**
	 * @author zhangming.luo
	 */
	public class SavePackageAction extends Action {
		private var dir : String;
		private var config : EditorConfig;
		private var quality : int;

		public function SavePackageAction(dir : String, config : EditorConfig, quality : int = 80) {
			this.quality = quality;
			this.config = config;
			this.dir = dir;
		}

		override public function execute() : void {
			super.execute();
			// 生成xml文档
			// packageWithSwift();
			// packageWithFlex();
			packageWithFlash();
			// 生成 分包
//			new SaveSmallPackageUtil(dir,config,quality);
			
		}

		protected function packageWithFlash() : void {
			var jsfl : String = <![CDATA[
				//pkg(fl.browseForFolderURL("请选择素材文件夹"),80);
				function pkg(folderPath,spriteName,quality){
					fl.trace("开始:"+spriteName);
					// 清理输出
					//fl.outputPanel.clear();
					// 创建新文件
					fl.createDocument();
					var dom = fl.getDocumentDOM();
					var lib = fl.getDocumentDOM().library;
					// 导入类
				 	FLfile.write(folderPath+"/ENTRY.as","package{import flash.display.*;public class ENTRY extends MovieClip{TEXTURE_CONF;TEXTURE;}}");
				 	dom.docClass="ENTRY";
					fl.trace("主脚本生成成功");
					FLfile.write(folderPath+"/TEXTURE_CONF.as","package{import flash.utils.*;[Embed(source=\""+spriteName+".xml\",mimeType=\"application/octet-stream\")]public class TEXTURE_CONF extends ByteArray {}}");
					fl.trace("导出配置文件成功");
					// 打开文件夹
					dom.importFile(folderPath + "/"+spriteName+".png");
					fl.trace("导入图片:"+folderPath + "/"+spriteName+".png"+"成功");
				 	lib.selectItem(spriteName+".png");
				 	// 清场
					dom.selectAll(); 
					dom.deleteSelection();
				 	// 导出位图链接
				 	lib.setItemProperty("allowSmoothing",false);
				 	lib.setItemProperty("linkageExportForAS",true);
				 	lib.setItemProperty("linkageExportInFirstFrame",true);
				 	lib.setItemProperty("linkageBaseClass","flash.display.BitmapData");
				 	lib.setItemProperty("linkageClassName","TEXTURE");
				 	lib.setItemProperty("compressionType","photo");
					lib.setItemProperty("quality",quality);
					fl.trace("导出图片成功");
					
					// 保存配置类
					fl.saveDocument(dom,folderPath+"/"+spriteName+".fla");
					dom.swfJPEGQuality=quality;
					dom.exportSWF(folderPath+"/"+spriteName+".swf",true);
					dom.close();
					FLfile.remove(folderPath+"/ENTRY.as");
					FLfile.remove(folderPath+"/TEXTURE_CONF.as");
					FLfile.remove(folderPath+"/"+spriteName+".fla");
					FLfile.remove(folderPath+"/"+spriteName+".jsfl");
					fl.trace("------------------------------------");
				}
			]]>;
			if (config.flash == null) {
				Log.alert("Flash没有找到");
				fault();
				return;
			}
			var flash : File = File.applicationDirectory.resolvePath(config.flash);
			if (!flash.exists) {
				Log.alert("Flash.exe没有找到");
				fault();
				return;
			}
			var workdir : File = File.applicationDirectory.resolvePath(dir);
			var out : FileStream = new FileStream();
			var jsflFile : File = workdir.resolvePath(config.projectName+".jsfl");
			out.open(jsflFile, FileMode.WRITE);
			out.writeByte(0xEF);
			out.writeByte(0xBB);
			out.writeByte(0xBF);
			out.writeUTFBytes(jsfl);
			out.writeUTFBytes(sprintf("pkg(\"file:///%s\",\"%s\",%d);", dir.replace(/\\/g, "/"), config.projectName, quality));
			out.close();
//			setTimeout(function():void{
//				run(flash, [jsflFile.nativePath], function() : void {
//					var interval : uint = setInterval(function() : void {
//						if (!workdir.resolvePath(config.projectName+".jsfl").exists) {
//							clearInterval(interval);
//							result();
//						}
//					}, 1000);
//				}, Log.info, Log.alert);
//			},1000);
		}

		protected function packageWithFlex() : void {
			var entryCode : String = <![CDATA[
				package{
					import flash.display.*;
					public class ENTRY extends Sprite{
						
					}
				}
			]]>;
			var textureCode : String = sprintf(<![CDATA[
				package{
			    	import flash.display.*;
					[Embed(source = "%s/texture.png", mimeType = "image/png", compression = "true", quality = "%s")]
    				public class TEXTURE extends Bitmap {
					}				
				}
			]]>, dir.replace(/\\/g, "/"), quality);
			var textureConfCode : String = sprintf(<![CDATA[
				package{
				    import flash.utils.*;
					[Embed(source="%s/config.xml",mimeType="application/octet-stream")]
    				public class TEXTURE_CONF extends ByteArray {
					}				
				}
			]]>, dir.replace(/\\/g, "/"));
			var tmpDir : File = File.createTempDirectory();
			var out : FileStream = new FileStream();
			var entryFile : File = tmpDir.resolvePath("ENTRY.as");
			out.open(entryFile, FileMode.WRITE);
			out.writeUTFBytes(entryCode);
			out.close();
			var textureFile : File = tmpDir.resolvePath("TEXTURE.as");
			out.open(textureFile, FileMode.WRITE);
			out.writeUTFBytes(textureCode);
			out.close();
			var textureConfigFile : File = tmpDir.resolvePath("TEXTURE_CONF.as");
			out.open(textureConfigFile, FileMode.WRITE);
			out.writeUTFBytes(textureConfCode);
			out.close();
			var java : File = File.applicationDirectory.resolvePath(config.jdk);
			var output : File = File.applicationDirectory.resolvePath(dir + "/" + config.projectName + ".swf");
			var flexHome : File = File.applicationDirectory.resolvePath("res");
			run(java, ["-jar", flexHome.nativePath + "/mxmlc.jar", entryFile.nativePath, "-source-path=" + tmpDir.nativePath, "-output=" + output.nativePath, "-includes=TEXTURE_CONF,TEXTURE", "-static-link-runtime-shared-libraries"], function() : void {
				result();
			}, Log.info, Log.alert, File.applicationDirectory.resolvePath(flexHome.nativePath));
		}

		protected function packageWithSwift() : void {
			var configXML : XML = <lib allowDomain="*"></lib>;
			configXML.appendChild(new XML(sprintf("<bitmap file=\"%s/texture.png\" compression=\"false\" quality=\"%d\" class=\"TEXTURE\"/>", dir, quality)));
			configXML.appendChild(new XML(sprintf("<bytearray file=\"%s/config.xml\" class=\"TEXTURE_CONF\"/>", dir)));
			var tmpFile : File = File.createTempFile();
			var out : FileStream = new FileStream();
			out.open(tmpFile, FileMode.WRITE);
			out.writeUTFBytes(configXML.toXMLString());
			out.close();
			// 执行打包
			var java : File = File.applicationDirectory.resolvePath(config.jdk);
			var output : File = File.applicationDirectory.resolvePath(dir + "/" + config.name + ".swf");
			run(java, ["-jar", File.applicationDirectory.resolvePath("res/Swift.jar").nativePath, "xml2lib", tmpFile.nativePath, output.nativePath], function() : void {
				result();
			}, Log.info, Log.alert);
		}

		private function run(file : File, arg : Array = null, exitHandler : Function = null, traceHandler : Function = null, errorHandler : Function = null, workingDirectory : File = null) : void {
			var nativeProcessStartupInfo : NativeProcessStartupInfo = new NativeProcessStartupInfo();
			nativeProcessStartupInfo.executable = file;
			nativeProcessStartupInfo.workingDirectory = workingDirectory;
			if (arg) {
				var vector : Vector.<String> = new Vector.<String>();
				vector.push.apply(null, arg);
				nativeProcessStartupInfo.arguments = vector;
			}
			var process : NativeProcess = new NativeProcess();
			if (dataHandler != null) {
				process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, dataHandler);
				process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, dataHandler);
			}
			if (exitHandler != null) {
				process.addEventListener(NativeProcessExitEvent.EXIT, exitHandler);
			}
			try
			{
				process.start(nativeProcessStartupInfo);
			} 
			catch(error:Error) 
			{
				Log.alert("我不报出错误来");
			}
			return;
			function dataHandler(event : Event) : void {
				var process : NativeProcess = event.currentTarget as NativeProcess;
				var str : String;
				if (event.type == ProgressEvent.STANDARD_OUTPUT_DATA) {
					str = process.standardOutput.readMultiByte(process.standardOutput.bytesAvailable, "gb2312").toString();
					if (traceHandler != null) {
						traceHandler(str);
					}
				} else {
					str = process.standardError.readMultiByte(process.standardError.bytesAvailable, "gb2312").toString();
					if (errorHandler != null) {
						errorHandler(str);
					}
				}
			}
		}
	}
}
